using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AOT;
using UnityEngine;
using UnityEngine.Networking;

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void strCallback(string value);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void intCallback(int value);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void floatCallback(float value);

public class JsCallAsync : MonoBehaviour
{
    #region 异步js

    //string
    [DllImport("__Internal")]
    public static extern void UnityAsyncStr(string key, string content,
        [MarshalAs(UnmanagedType.FunctionPtr)] strCallback result);

    [DllImport("__Internal")]
    public static extern string StringToBuffer(string key);

    //int
    [DllImport("__Internal")]
    public static extern void UnityAsyncInt(int x, int y,
        [MarshalAs(UnmanagedType.FunctionPtr)] intCallback result);

    #endregion

    [MonoPInvokeCallback(typeof(strCallback))]
    public static void ResultStr(string value)
    {
        Debug.Log($"[unity.ResultStr] js back result===>{value}");
    }

    [MonoPInvokeCallback(typeof(intCallback))]
    public static void ResultInt(int value)
    {
        Debug.Log($"[unity.ResultInt] js back result===>{value}");
    }

    private string key = "hello";
    private string content = "test";

    private int x;
    private int y;

    private void OnGUI()
    {
        GUILayout.Label($"string==> key:{key},content:{content}");
        key = GUILayout.TextArea(key, GUILayout.Width(200));
        content = GUILayout.TextArea(content, GUILayout.Width(400));
        if (GUILayout.Button("JsCall.UnityAsync callback string"))
        {
            UnityAsyncStr(key, content, ResultStr);
        }

        GUILayout.Space(50);

        GUILayout.Label($"int==> x:{x},y:{y}");
        x = (int)GUILayout.HorizontalSlider(x, -10f, 100f);
        y = (int)GUILayout.HorizontalSlider(y, -10f, 100f);
        if (GUILayout.Button("JsCall.UnityAsync callback int: add"))
        {
            UnityAsyncInt(x, y, ResultInt);
        }
    }
}